import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { RouteMeta, type RouteRecordRaw } from "vue-router"
import { constantRoutes, dynamicRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"
import { useUserStoreHook } from "./user"
import { INode } from "@/api/login/types/login"
import { cloneDeep } from "lodash-es"
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}

const filterDynamicRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterDynamicRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

export const usePermissionStore = defineStore("permission", () => {
  /** 可访问的路由 */
  const routes = ref<RouteRecordRaw[]>([])
  /** 有访问权限的动态路由 */
  const addRoutes = ref<RouteRecordRaw[]>([])
  const routerTree = ref<RouteRecordRaw[]>([])
  const userStore = useUserStoreHook()

  /** 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由） */
  const setRoutes = (roles: string[]) => {
    const accessedRoutes = filterDynamicRoutes(dynamicRoutes, roles)
    _set(accessedRoutes)
  }

  /** 所有路由 = 所有常驻路由 + 所有动态路由 */
  const setAllRoutes = () => {
    _set(dynamicRoutes)
  }

  // 过滤路由 构建一棵新的路由树
  const filterRouter = (allRouter: RouteRecordRaw[], permissionRouter: INode[]) => {
    allRouter.forEach((routerItem) => {
      const targetPermission = permissionRouter.find(
        (permissionRouter) => permissionRouter.node_name === routerItem.name
      )

      if (targetPermission) {
        // 是否是父级菜单
        if (!targetPermission.node_pid) {
          if (routerItem.meta) routerItem.meta.id = targetPermission.id
          const treeItem = cloneDeep(routerItem)
          treeItem.children = []
          routerTree.value.push(treeItem)
        } else {
          const parent = routerTree.value.find((router) => (router.meta as RouteMeta).id === targetPermission.node_pid)
          parent?.children?.push(routerItem)
        }

        if (routerItem.children) filterRouter(routerItem.children, targetPermission.children)
      }
    })
  }

  const _set = (accessedRoutes: RouteRecordRaw[]) => {
    routerTree.value = []
    routes.value = constantRoutes.concat(accessedRoutes)
    addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes

    filterRouter(routes.value, userStore.permissionRouter)
    routes.value = routerTree.value
  }

  return { routes, addRoutes, setRoutes, setAllRoutes }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
